<template lang="html">
  <div class="fm">
    <FMHeader
    title="君弘FM"
    :showTitleText="showTitleText"/>

    <div class="currentArticle">

      <div class="text_wrapper">
        <div class="text_content" ref="scroll_div">
          <div class="scroll_begin" ref="scroll_begin">
            {{currentArticle.summary}}
          </div>
          <div class="scroll_end" ref="scroll_end"></div>
        </div>

        <div class="text_info">
          <div class="ico">
            <i class="iconfont2 icon-bofang"></i>
            <!-- <img src="../assets/images/icon_play_number@2x.png" alt=""> -->
          </div>

          <div>{{ curArticleBrowse | viewNum }}次</div>
          <div>{{ currentArticle.otime | fromNow }}</div>
        </div>
      </div>

    </div>
    <div class="audioWrap">
      <audio-play
        @prev="changeAudioPrev"
        @next="changeAudioNext"
        @loadCompleted="audioLoadCompleted"
        :isFirstAudio="isFirstAudio"
        :isLastAudio="isLastAudio"
        ref="audio"/>
    </div>
    <div class="article" ref="article">
      <div class="tab" ref='tab'>
        <div class="articleList current" @click="showArticleList" ref="articleList">
          列表
        </div>
        <div class="articleDetail" @click="showArticleDetail" ref="articleDetail">
          文稿详情
        </div>
      </div>
      <div class="content">
        <div  v-if="!showDetail">
          <load-more
            :bottom-method="loadBottom"
            :auto-fill="false"
            ref="loadmore">
            <template v-for="(item, index) in articleDataHandled">
              <articleItem
                :summary="item.summary"
                :time ="item.otime"
                :browseInfo="item.browseInfo"
                :isPlay="item.curPlay"
                :curIndex="index"
                :audioIsPlaying="audioIsPlaying"
                :audioLoadCompleted="dataLoaded"
                @play="play"
                :key="index"
                />
            </template>
          </load-more>
        </div>
        <articleDetail
          :summary="currentArticle.summary"
          :contentUrl="currentArticle.contentUrl"
          :browseInfo="currentArticle.browseInfo"
          :hasCollect="currentArticle.hasCollect"
          @save-success="saveSuccess"
          @cancel-success="cancelSuccess"
          @changeCollectStatus='changeCollectStatus'
        v-else/>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import FMHeader from '@/components/FM/Header.vue'
import ArticleItem from '@/components/FM/Article.vue'
import ArticleDetail from '@/components/FM/ArticleDetail.vue'
import AudioPlay from '@/components/player/index.vue'
import LoadMore from '@/components/LoadMore.vue'
import Vue from 'vue'
import { getArticles, Article, getReadCount, readArticle, NewsCount } from '../api'
import { fromNow } from '../util/timeUtil'
import { numberToArab } from '../util/numberUtil'
import { eventTrack } from '../util/decorator'

interface FMdata {
  timer: any;
  timeout: any;
  dataLoaded: boolean;
  showTitleText: boolean;
  showDetail: boolean;
  currentArticle: any;
  articleList: Article[];
  articleDataHandled: Article[];
  pageNum: number;
  isFirstAudio: boolean;
  isLastAudio: boolean;
  bodyScroll: number;
  curArticleBrowse: number;
  audio: any;
  newsIds: string[];
  btnGropPosTop: number;
  playerBtnGroup: any;
  articleDOM: any;
  articleListDOM: any;
  articleDetailDOM: any;
  scrollBeginDOM: any;
  scrollEndDOM: any;
  tabDOM: any;
  scrollDivDOM: any
}

// let timer: any, timeout: any
export default Vue.extend({
  data () {
    const initialState: FMdata = {
      timer: null,
      timeout: null,
      dataLoaded: true,
      showTitleText: true,
      showDetail: false,
      currentArticle: {},
      articleList: [],
      articleDataHandled: [],
      pageNum: 1,
      isFirstAudio: true,
      isLastAudio: false,
      bodyScroll: 0,
      curArticleBrowse: 0,
      newsIds: [],
      audio: '',
      btnGropPosTop: 0,
      playerBtnGroup: '',
      articleDOM: '',
      articleListDOM: '',
      articleDetailDOM: '',
      scrollBeginDOM: '',
      scrollEndDOM: '',
      tabDOM: '',
      scrollDivDOM: ''
    }
    return initialState
  },
  components: {
    FMHeader,
    ArticleItem,
    ArticleDetail,
    AudioPlay,
    LoadMore
  },
  created () {

  },
  filters: {
    fromNow(ts: string): string {
      return fromNow(parseInt(ts))
    },

    viewNum(num: string): string {
      return  numberToArab(num + '')
    }
  },
  computed: {
    audioIsPlaying ():boolean {
      if (this.audio) {
        return this.audio.playing
      }
      else {
        return false
      }
    }
  },
  mounted () {
    this.initScroll ()
    this.initDOM()
    this.initData()
    window.addEventListener('scroll', this.handleTabPos)
    eventTrack('007001')

  },
  methods: {
    initData () {
      getArticles(this.pageNum).then(res => {
        this.articleList = res.data
        this.getBrowseInfo()
        this.change(0)
        this.audio.canPlay = true
        this.dataLoaded = true
        // this.$nextTick(()=> {
        //   this.audio.load()
        //   this.audio.play()
        // })
      })
    },
    initDOM () {
      this.articleListDOM = this.$refs.articleList
      this.articleDetailDOM = this.$refs.articleDetail
      this.articleDOM = this.$refs.article,
      this.articleListDOM = this.$refs.articleList
      this.articleDetailDOM = this.$refs.articleDetail
      this.scrollBeginDOM = this.$refs.scroll_begin
      this.scrollEndDOM = this.$refs.scroll_end
      this.tabDOM = this.$refs.tab
      this.scrollDivDOM = this.$refs.scroll_div
      this.audio = this.$refs.audio
    },
    initScroll () {
      const playerComponent: any = this.$children.find(item => item.$el.classList.contains('player__wrapper'))
      this.playerBtnGroup = <any>playerComponent.$refs.playerBtnGroup
      this.btnGropPosTop = this.playerBtnGroup.getBoundingClientRect().top - 45
      window.addEventListener('scroll', this.handleScroll)
    },
    getBrowseInfo () {
      this.newsIds = this.articleList.map(item => item.id)
      getReadCount(this.newsIds).then(res => {
        const data = res.data
        console.info(data)
        this.articleList.forEach((item, index) => {
          this.$set(item, "browseInfo", data[`news_${item.id}`])
          this.$set(item, 'hasCollect', false)
        })
        this.articleDataHandled = this.articleList
        this.curArticleBrowse = this.currentArticle.browseInfo.browse
      })
    },
    showArticleList () {
      eventTrack('007005')

      if (!this.articleListDOM.classList.contains('current')) {
        this.articleListDOM.classList.add('current')
        this.articleDetailDOM.classList.remove('current')
        this.showDetail = false
        window.scrollTo(0, this.bodyScroll)
      } else {
        return
      }
    },
    showArticleDetail () {
      eventTrack('007007')
      if (!this.articleDetailDOM.classList.contains('current')) {
        this.bodyScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        window.scrollTo(0, 0)
        this.articleDetailDOM.classList.add('current')
        this.articleListDOM.classList.remove('current')
        this.showDetail = true
      } else {
        return
      }
    },
    /**
     * 文章收藏成功
     */
    saveSuccess (): void {
      this.currentArticle.browseInfo.store = parseInt(this.currentArticle.browseInfo.store) + 1 + ''
      this.currentArticle.hasCollect = true
      // console.log(this.currentArticle.browseInfo.store)
    },
    /**
     * 文章取消收藏
     */
    cancelSuccess (): void {
      this.currentArticle.browseInfo.store = parseInt(this.currentArticle.browseInfo.store) - 1 + ''
      this.currentArticle.hasCollect = false
    },

    /**
     * 改变收藏的状态
     */
    changeCollectStatus (val: boolean): void {
      this.currentArticle.hasCollect = val
    },

    /**
     * 文章分享成功
     */
    shareSuccess(): void {
      this.currentArticle.browseInfo.share = parseInt(this.currentArticle.browseInfo.share) + 1 + ''
    },

    /**
     * 切换文章
     */
    play (curIndex: number) {
      this.change(curIndex)
      this.loadAudio()
    },

    change(curIndex: number) {
      if (curIndex === this.articleList.findIndex(item => item === this.currentArticle)) return
      eventTrack('007006')
      for (let item of (<any>Object).values(this.articleList)) {
        item.curPlay = false
      }
      this.articleList[curIndex].curPlay = true
      this.currentArticle = <Article>this.articleList.find(item => item.curPlay)
      // console.warn('id',this.currentArticle.id)
      readArticle(this.currentArticle.id)
      this.initMarquee()
      this.audio.changeAudio(this.articleList[curIndex].yuyinUrl)
    },

    loadAudio () {
      this.$nextTick(() => {
        this.audio.load()
        this.audio.play()
      })
    },

    initMarquee () {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.$nextTick(() => {
        this.scrollDivDOM.scrollLeft = 0
        if (this.scrollBeginDOM.offsetWidth > this.scrollDivDOM.offsetWidth) {
          this.scrollEndDOM.textContent = this.scrollBeginDOM.textContent
          if (this.timeout) {
            clearTimeout(this.timeout)
            this.timeout = null
          }
          this.timeout = setTimeout(() => {
            this.timer = setInterval(this.Marquee, 30)
          }, 2000)
        } else {
          this.scrollEndDOM.textContent = ''
        }
      })
    },
    Marquee () {
      if (this.scrollEndDOM.offsetWidth - this.scrollDivDOM.scrollLeft <= 0) {
        this.scrollDivDOM.scrollLeft = 0
      } else {
        this.scrollDivDOM.scrollLeft++
      }
    },
    handleTabPos () {
      if (this.tabDOM.getBoundingClientRect().top <= 45) {
        this.tabDOM.style.position = 'fixed'
        this.tabDOM.style.top = '45px'
      }
      if (this.articleDOM.getBoundingClientRect().top >= 45) {
        this.tabDOM.style.position = 'absolute'
        this.tabDOM.style.top = '0'
      }
    },
    hideTitle () {
      if (!this.showTitleText) return
      this.showTitleText = false
    },
    showTitle () {
      if (this.showTitleText) return
      this.showTitleText = true
    },
    loadBottom () {
      const loadmore: any = this.$refs.loadmore
      this.pageNum++
      getArticles(this.pageNum).then(res => {
        console.warn('res', res)
        if(res.data.length !== 0) {
          let ind = -2
          for (let i = 0;i < this.articleList.length; i++) {
            ind = res.data.findIndex(item => item.otime === this.articleList[i].otime)
            if ( ind !== -1) {
              break
            }
          }
          if(ind !== -2 && ind !== -1) {
            const newdata = res.data.slice(ind + 1)
            this.articleList = [...this.articleList, ...newdata]
            this.getBrowseInfo()
            loadmore.onBottomLoaded()
          } else {
            this.articleList = [...this.articleList, ...res.data]
            this.getBrowseInfo()
            loadmore.onBottomLoaded()
          }
        } else if (res.data.length == 0) {
          loadmore.onBottomAllLoaded()
        }
      }).catch ((err: any )=> {
        console.warn(err)
        loadmore.onBottomAllLoaded()
      })
    },
    changeAudioPrev () {
      let ind = this.articleList.findIndex(item => item === this.currentArticle)
      this.play(--ind)
    },
    changeAudioNext () {
      let ind = this.articleList.findIndex(item => item === this.currentArticle)
      this.play(++ind)
    },
    handleScroll () {
      const btnGroup:any = this.playerBtnGroup
      let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
      if (scrollTop >= this.btnGropPosTop) {
        btnGroup.style.position = 'fixed'
        btnGroup.style.transform = 'scale(0.6)'
        btnGroup.style.top = '8px'
        this.hideTitle()
      }
      if (scrollTop < this.btnGropPosTop) {
        btnGroup.style.position = 'absolute'
        btnGroup.style.top = '45px'
        btnGroup.style.transform = 'scale(1)'
        this.showTitle()
      }
    },
    audioLoadCompleted (val: boolean) {
      this.dataLoaded = val
      // this.$toast(val)
    }
  },
  watch: {
    currentArticle (val) {
      if (val.browseInfo) {
        this.curArticleBrowse = val.browseInfo.browse
        let ind = this.articleList.findIndex(item => item === this.currentArticle)
        if (ind === 0) {
          this.isFirstAudio = true
        } else if (ind === this.articleList.length - 1) {
          this.isLastAudio = true
        } else {
          this.isFirstAudio = false
          this.isLastAudio = false
        }
      }
    }
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleTabPos)
    window.removeEventListener('scroll', this.handleScroll)
  }
})
</script>

<style lang="less" scoped>
@import '../assets/less/mixins.less';

.fm {
  padding-top: 45px;
  box-sizing: border-box;
  background-color: #F6F6F6;
}
.current {
  color: #309FEA;
  border-bottom: 2px solid  #309FEA !important;
}
.currentArticle {
  background-color: #26A8FF;
  padding: 0 15px 15px;
}
.audioWrap {
  background-color: #26A8FF;
  min-height: 100px;
  padding: 0 15px;
  box-sizing: border-box;
}
.article {
  background-color: #fff;
  padding-top: 40px;
  position: relative;
  margin-top: 7px;
  .tab {
    position: absolute;
    z-index: 2000;
    background-color: #fff;
    // background-color: transparent;
    top: 0;
    left: 0;
    height: 40px;
    width: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    border-bottom: 1px solid #EAEAEA;

    & > div {
      width: 24%;
      height: 100%;
      .flexLayout();
      border-bottom: 2px solid  transparent;
      box-sizing: border-box;
    }
  }
  .content {
    padding: 0px 15px 0px 15px;
  }
}
.text_wrapper {
  color: #fff;
  display: flex;
  min-height: 42px;
  padding: 10px 0 0 0;
  flex-direction: column;
  .text_content {
    overflow: hidden;
    white-space: nowrap;
    text-align: left;
    font-size: 0;
    margin-bottom: 3px;
    // line-height: 20px;
    .ellipsis(2);
  }
}
.text_info {
  font-size: 12px;
  height: 20px;
  display: flex;
  .flexLayout(left);
  .ico {
    display: flex;
    align-items: center;
    height: 100%;
    transform: scale(0.8);
    box-sizing: border-box;

    i {
      font-size: 16px;
    }
  }
  div:nth-child(2){
    margin: 0 15px 0 4px;
  }
}
.scroll_begin, .scroll_end {
  font-size: 16px;
  display: inline-block;
  padding-right: 50px;
}

</style>
